<template>
  <div>
    <el-row>
      <el-col :span="22">
        <el-alert
          :title="infoAlert.title"
          :type="infoAlert.type"
          center
          show-icon
          :closable="false"
          style="margin-bottom: 15px"
        ></el-alert>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
          v-print="'#formTable'"
          style="float: right"
          @click="handlePrint"
          >打印</el-button
        >
      </el-col>
    </el-row>
    <el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                v-model="form.projectName"
                placeholder="请输入项目名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectOn">
              <el-input
                v-model="form.projectOn"
                placeholder="请输入项目编号"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="立项时间" prop="projectTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.projectTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择立项时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申请人" prop="applyUser">
              <el-select
                v-model="form.applyUser"
                placeholder="请选择申请人"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="chargeUser">
              <el-select
                v-model="form.chargeUser"
                placeholder="请选择负责人"
                style="width: 100%"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="user in userList"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目性质" prop="nature">
              <el-radio-group v-model="form.nature">
                <el-radio
                  v-for="dict in dict.type.crm_order_nature"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订单位" prop="laborContracts">
              <el-radio-group v-model="form.laborContracts">
                <el-radio
                  v-for="dict in dict.type.crm_order_contracts"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endTime">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerId">
              <el-select
                v-model="form.customerId"
                placeholder="请选择客户名称"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="customer in customerList"
                  :key="customer.customerId"
                  :label="customer.customerName"
                  :value="customer.customerId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目金额" prop="projectSum">
              <el-input v-model="form.projectSum" placeholder="请输入项目金额">
                <template slot="append">{{
                  digitUppercase(form.projectSum)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预计利润" prop="profit">
              <el-input
                v-model="form.profit"
                placeholder="请输入预计利润"
                readonly
              >
                <template slot="append">{{
                  digitUppercase(form.profit)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="利润率" prop="profitMargin">
              <el-input
                v-model="form.profitMargin"
                placeholder="请输入利润率"
                readonly
              >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款方式" prop="paymentTime">
              <el-input
                v-model="form.paymentTime"
                placeholder="请输入付款方式"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-divider>项目预算成本费用支出</el-divider>
            <el-form-item label="费用明细" prop="details" class="details">
              <el-table :data="form.detailsList" style="width: 100%">
                <el-table-column label="费用类型" prop="detailsName">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.detailsType"
                      placeholder="请选择费用类型"
                      style="width: 100%"
                      :disabled="
                        scope.row.isRequired === '1' || scope.row.flag === '1'
                      "
                    >
                      <el-option
                        v-for="dict in dict.type.crm_fee_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="费用名称" prop="detailsName">
                  <template slot-scope="scope">
                    <el-input
                      :readonly="scope.row.flag === '1'"
                      v-model="scope.row.detailsName"
                      placeholder="请输入费用名称"
                      :disabled="scope.row.isRequired === '1'"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="费用描述" prop="detailsDesc">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.detailsDesc"
                      placeholder="请输入费用详情描述"
                      :disabled="scope.row.isRequired === '1'"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="预算合计" prop="detailsAmount">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.detailsAmount"
                      placeholder="请输入预算合计"
                      type="number"
                      :disabled="scope.row.isRequired === '1'"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="请输入备注"
                      :disabled="scope.row.isRequired === '1'"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="是否存在明细"
                  prop="isRequired"
                  width="100"
                >
                  <template slot-scope="scope">
                    <el-checkbox
                      :value="scope.row.isRequired === '1'"
                      @change="(val) => handleCheckboxChange(scope.row, val)"
                      :disabled="
                        scope.row.detailsAmount !== null &&
                        scope.row.detailsAmount !== ''
                      "
                      >无</el-checkbox
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                  width="100"
                  class-name="small-padding fixed-width"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-plus"
                      @click="addExpenses(scope)"
                      >新增</el-button
                    >
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      v-if="scope.row.flag !== '1'"
                      @click="delExpenses(scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                style="margin: 10px 45% 0"
                @click="addExpenses(null)"
                >其他明细新增</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="费用总计" prop="aggregationCharge">
              <el-input
                readonly
                v-model="form.aggregationCharge"
                placeholder="请输入费用总计"
              >
                <template slot="append">{{
                  digitUppercase(form.aggregationCharge)
                }}</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="管理层意见" prop="opinion">
              <el-input v-model="form.opinion" placeholder="请输入管理层意见" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="url">
              <file-upload v-model="form.url" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!disabled">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="submitForm('1')"
                >提 交</el-button
              >
              <el-button type="info" @click="submitForm('0')">暂 存</el-button>
              <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <project-approval
      id="formTable"
      :tabledata="form"
      :ownerList="userList"
      :customerList="customerList"
      :deptOptions="deptOptions"
      v-show="showProjectApproval"
    />
  </div>
</template>

<script>
import {
  listOrderRegister,
  addOrderRegister,
  updateOrderRegister,
  getOrderRegisterInfo,
} from "@/api/crm/orderRegister";

import { deptTreeSelect } from "@/api/system/user";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import projectApproval from "../components/projectApprovalPrint.vue";
export default {
  name: "OrderRegister",
  dicts: ["crm_order_nature", "crm_order_contracts", "crm_fee_type"],
  props: {
    userList: {
      type: Array,
      default: [],
    },
    customerList: {
      type: Array,
      default: [],
    },
    orderInfo: {
      type: Object,
      default: () => {},
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    Treeselect,
    projectApproval,
  },
  data() {
    return {
      infoAlert: {
        type: "info",
        title: "待填写",
      },
      // 商机项目立项表格数据
      orderRegisterList: [],
      // 弹出层标题
      title: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "商机id不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "所属部门id不能为空", trigger: "blur" },
        ],
        projectOn: [
          { required: true, message: "项目编号不能为空", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
        ],
        projectTime: [
          { required: true, message: "立项时间不能为空", trigger: "blur" },
        ],
        customerId: [
          { required: true, message: "客户id不能为空", trigger: "blur" },
        ],
        applyUser: [
          { required: true, message: "申请人id不能为空", trigger: "blur" },
        ],
        chargeUser: [
          { required: true, message: "负责人不能为空", trigger: "blur" },
        ],
        nature: [
          { required: true, message: "项目性质不能为空", trigger: "change" },
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
        ],
        projectSum: [
          { required: true, message: "项目金额不能为空", trigger: "blur" },
        ],
        profit: [
          { required: true, message: "预计利润不能为空", trigger: "blur" },
        ],
        profitMargin: [
          { required: true, message: "利润率不能为空", trigger: "blur" },
        ],
        aggregationCharge: [
          { required: true, message: "费用总计不能为空", trigger: "blur" },
        ],
        laborContracts: [
          { required: true, message: "签订单位不能为空", trigger: "change" },
        ],
        paymentTime: [
          { required: true, message: "付款方式不能为空", trigger: "change" },
        ],
        details: {
          required: true,
          validator: this.validateDetails,
          trigger: "change",
        },
      },
      deptOptions: [],
      showProjectApproval: false,
    };
  },
  created() {},
  watch: {
    "form.projectSum"() {
      // 计算公司明细
      let obj = this.form.detailsList?.find(
        (item) => "公司明细" === item.detailsName
      );
      obj.detailsAmount = (this.form.projectSum * 0.03).toFixed(2);
    },
    "form.detailsList": {
      handler(val) {
        // 计算支出总金额
        const totalAmount = this.form.detailsList?.reduce((sum, item) => {
          const amount = parseFloat(item.detailsAmount) || 0;
          return sum + amount;
        }, 0);

        // 计算利润
        const profit = (this.form.projectSum - totalAmount).toFixed(2);
        this.$set(this.form, "profit", profit);

        // 计算利润率
        const profitMargin =
          this.form.projectSum > 0
            ? ((profit / this.form.projectSum) * 100).toFixed(2)
            : "0";
        this.$set(this.form, "profitMargin", profitMargin);

        this.form.aggregationCharge = totalAmount;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handlePrint() {
      this.showProjectApproval = true;
      setTimeout(() => {
        this.showProjectApproval = false;
      }, 2000);
    },
    handleCheckboxChange(row, val) {
      row.isRequired = val ? "1" : "0";
    },
    async getData() {
      await this.getDeptTree();
      await this.getOrderRegisterInfo();
    },
    getOrderRegisterInfo() {
      getOrderRegisterInfo({ orderId: this.orderInfo.orderId }).then((res) => {
        this.form = res.data;
        if (this.form) {
          // 根据审核状态设置提示
          switch (this.form.auditStatus) {
            case "0":
              this.infoAlert = { type: "info", title: "待提交" };
              break;
            case "1":
              this.infoAlert = { type: "warning", title: "待审核" };
              break;
            case "2":
              this.infoAlert = { type: "success", title: "审核通过" };
              break;
            case "3":
              this.infoAlert = { type: "error", title: "审核不通过" };
              break;
            case "4":
              this.infoAlert = { type: "warning", title: "审核中" };
              break;
          }

          this.form.chargeUser = this.form.chargeUser
            ? this.form.chargeUser.split(",")
            : null;
        } else {
          (this.infoAlert = {
            type: "info",
            title: "待填写",
          }),
            // 未填写则进行数据回显
            (this.form = {
              nature: "1",
              laborContracts: "0",
              projectOn: "立项表提交后自动生成",
              deptId: this.$store.getters.deptId,
              projectName: this.orderInfo.orderName,
              customerId: this.orderInfo.customerId,
              applyUser: this.orderInfo.userId,
              chargeUser: [this.orderInfo.userId],
              projectSum: this.orderInfo.planAmount,
              projectTime: new Date(),
              startTime: new Date(),
              detailsList: [
                {
                  detailsName: "采购明细",
                  detailsType: "0",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "外援明细",
                  detailsType: "1",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "工单明细",
                  detailsType: "2",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "差旅明细",
                  detailsType: "3",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "软件研发明细",
                  detailsType: "4",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "税金明细",
                  detailsType: "5",
                  detailsDesc: null,
                  detailsAmount: null,
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
                {
                  detailsName: "公司明细",
                  detailsType: "6",
                  detailsDesc: "公司管理费",
                  detailsAmount: (this.orderInfo.planAmount * 0.03).toFixed(2),
                  remark: null,
                  isRequired: "0",
                  flag: "1",
                },
              ],
            });
        }
      });
    },
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    validateDetails(rule, value, callback) {
      const isValid = this.form.detailsList.every((item) => {
        return (
          (item.detailsName && item.detailsAmount) || item.isRequired === "1"
        );
      });
      if (!isValid) {
        callback(new Error("费用名称和预算合计必须填写，否则选无"));
      } else {
        callback();
      }
    },
    // 表单重置
    reset() {
      this.form = {
        nature: "1",
        laborContracts: "0",
        projectOn: "立项表提交后自动生成",
        deptId: this.$store.getters.deptId,
        projectName: this.orderInfo.orderName,
        customerId: this.orderInfo.customerId,
        applyUser: this.orderInfo.userId,
        chargeUser: [this.orderInfo.userId],
        projectSum: this.orderInfo.planAmount,
        projectTime: new Date(),
        startTime: new Date(),
        detailsList: [
          {
            detailsName: "采购明细",
            detailsType: "0",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "外援明细",
            detailsType: "1",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "工单明细",
            detailsType: "2",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "差旅明细",
            detailsType: "3",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "软件研发明细",
            detailsType: "4",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "税金明细",
            detailsType: "5",
            detailsDesc: null,
            detailsAmount: null,
            remark: null,
            isRequired: "0",
            flag: "1",
          },
          {
            detailsName: "公司明细",
            detailsDesc: "公司管理费",
            detailsType: "6",
            detailsAmount: (this.orderInfo.planAmount * 0.03).toFixed(2),
            remark: null,
            isRequired: "0",
            flag: "1",
          },
        ],
      };
      this.resetForm("form");
    },
    cancel() {
      this.reset();
      this.$emit("cancel");
    },
    addExpenses(scope) {
      if (scope) {
        this.form.detailsList.splice(scope.$index + 1, 0, {
          detailsName: scope.row.detailsName,
          detailsType: scope.row.detailsType,
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
        });
      } else {
        this.form.detailsList.push({
          detailsName: null,
          detailsType: '7',
          detailsDesc: null,
          detailsAmount: null,
          remark: null,
          isRequired: "0",
          flag: "0",
        });
      }
    },
    delExpenses(index) {
      this.form.detailsList.splice(index, 1);
    },
    /** 查询商机项目立项列表 */
    getList() {
      this.loading = true;
      listOrderRegister(this.queryParams).then((response) => {
        this.orderRegisterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm(auditStatus) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.orderId = this.orderInfo.orderId;
          
          this.form.auditStatus = auditStatus;
          let obj = {...this.form}
          obj.chargeUser = this.form.chargeUser.join(",");
          if (this.form.orderRegisterId != null) {
            updateOrderRegister(obj).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getOrderRegisterInfo();
            });
          } else {
            addOrderRegister(obj).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getOrderRegisterInfo();
            });
          }
        }
      });
    },
  },
};
</script>

<style scoped>
::v-deep .details .el-table--medium .el-table__cell {
  padding: 0;
  border-bottom: none;
}

::v-deep .details .el-input--medium {
  margin: 10px 10px 10px -10px;
}
</style>